package com.hockeo.server.rpc.command.user.executors;

import javax.servlet.http.HttpServletRequest;

import com.google.appengine.api.users.User;
import com.google.appengine.api.users.UserService;
import com.google.appengine.api.users.UserServiceFactory;
import com.hockeo.server.data.DAO;
import com.hockeo.server.rpc.command.CommandExecutionContext;
import com.hockeo.server.rpc.command.ICommandExecutor;
import com.hockeo.shared.VHUtil;
import com.hockeo.shared.domain.persistent.Manager;
import com.hockeo.shared.domain.transitory.SessionInfo;
import com.hockeo.shared.rpc.command.error.ExecutionFailedException;
import com.hockeo.shared.rpc.command.user.commands.GetSessionInfo;
import com.hockeo.shared.rpc.command.user.responses.GotSessionInfo;
import com.hockeo.tinygds.TKey;
import com.hockeo.tinygds.TinyGDS;

public class GetSessionInfoExecutor implements ICommandExecutor<GetSessionInfo, GotSessionInfo>
{
  @Override
  public GotSessionInfo execute( CommandExecutionContext ctx, GetSessionInfo cmd )
      throws ExecutionFailedException
  {
    UserService userService = UserServiceFactory.getUserService();
    User user = userService.getCurrentUser();
    SessionInfo si;

    if ( user != null )
    {
      TinyGDS tgds = DAO.get().begin();
      Manager manager = tgds.find( new TKey<Manager>( Manager.class, user.getUserId() ) );
      HttpServletRequest rq = ctx.getRequest();

      // if the manager does not yet exist in the database create it, otherwise update it
      //
      if ( manager == null )
        manager = new Manager( user.getUserId(), user.getEmail(), rq.getRemoteAddr(), rq.getLocale().toString() );
      else
        manager.update( user.getEmail(), rq.getRemoteAddr(), rq.getLocale().toString() );

      tgds.put( manager );

      si = new SessionInfo( manager, userService.createLogoutURL( VHUtil.URL_WELCOME_PAGE ) );
    }
    else
      si = new SessionInfo( null, userService.createLoginURL( VHUtil.URL_WELCOME_PAGE ) );

    return new GotSessionInfo( si );
  }

  @Override
  public Class<GetSessionInfo> getCommandType()
  {
    return GetSessionInfo.class;
  }
}
